package com.tian.authen.exception;

import com.tian.common.AuthResultCode;
import com.tian.common.result.BaseResult;
import com.tian.common.result.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidRequestException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * <pre>
 *     认证客户端信息抛出的自定义异常
 * </pre>
 * @author zhumengping
 * @title: OauthServerWebResponseException
 * @projectName zhump-cloud
 * @date 2023/8/9 9:45
 */
public class OauthServerWebResponseException implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity<BaseResult> translate(Exception e) throws Exception {
        BaseResult baseResult = doTranslateHandler(e);
        return new ResponseEntity(baseResult, HttpStatus.UNAUTHORIZED);

    }

    private BaseResult doTranslateHandler(Exception e){
        AuthResultCode unauthorized = AuthResultCode.UNAUTHORIZED;
        if (e instanceof UnsupportedGrantTypeException || e instanceof InvalidRequestException){
            unauthorized = AuthResultCode.UNSUPPORTED_GRANT_TYPE;
        }else if (e instanceof InvalidGrantException){
            unauthorized = AuthResultCode.USERNAME_OR_PASSWORD_ERROR;
        }
        return Result.wrap(unauthorized.getCode(),unauthorized.getMsg());

    }
}
